<?php
//部门
namespace app\crm\controller;

use app\crm\model\Sys;
use think\Config;
use think\Request;
use think\Exception;
use app\crm\model\Department as DepartmentModel;
use app\crm\model\Staff as StaffModel;
use app\crm\model\Cusarea as CusareaModel;
class Roletree extends \CrmController
{
    static private $DiDuiBumen = [];
   
    public function getnum(){
         $model=new CusareaModel();
        $c=db("crm_rule_staff")->alias("a")->join("sh_crm_staff b","a.staff_id=b.staff_id")->where("b.is_downstream=1")->count();
        if(!$c){
            $c=0;
        }
        return $c;
               
    }
    public function renamegroup(Request $request){
        try{
            $model=new CusareaModel();
            $params = delToken($request->get());
            $group_id=trim($params["group_id"]);
            $group_name=trim($params["group_name"]);
            if(!$group_name)
                \exception("小组名为空");
            $has=db("crm_rule_power_group")->where("group_name='{$group_name}' and group_id<>$group_id")->find();
            if($has){
                \exception("小组名已存在");
            }else{
                db("crm_rule_power_group")->where(["group_id"=>$group_id])->update(["group_name"=>$group_name]);

            }
            $this->successTerminate($params);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function copygroup(Request $request){
        try{
            
            $model=new CusareaModel();
            $params = delToken($request->get());
            $group_id=trim($params["group_id"]);
            $group_name=trim($params["group_name"]);
            if(!$group_name)
                \exception("小组名为空");
            $has=db("crm_rule_power_group")->where("group_name='{$group_name}'")->find();
            if($has){
                \exception("小组名已存在");
            }else{
                $newid=db("crm_rule_power_group")->insertGetId(["group_name"=>$group_name,"copy_by"=>$group_id]);
                $power=db("crm_rule_power")->where(["type"=>2,"obj_id"=>$group_id])->find();
                if($power){
                    $newpower=$power;
                    unset($newpower["power_id"]);
                    $newpower["obj_id"]=$newid;
                    db("crm_rule_power")->insert($newpower);
                }

            }
            $this->successTerminate($params);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function delpowergroup(Request $request){
        try{
            $model=new CusareaModel();
            $params = delToken($request->get());
            $group_id=trim($params["group_id"]);
            $c=$this->getgc($group_id);
            if($c){
                \exception("小组存在成员不能删除");
            }else{
                db("crm_rule_power_group")->where(["group_id"=>$group_id])->delete();
            }
            $this->successTerminate($params);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function getgc($group_id){
        $c=db("crm_rule_power_user")->where(["group_id"=>$group_id])->count();
        return $c;
    }
    public function addgroup(Request $request){
        try{
            $StaffModel = new \app\crm\model\Staff();
            $params = delToken($request->get());
            $data["group_name"]=trim($params["group_name"]);
            if(!$data["group_name"])
                \exception("小组名为空");
            $has=db("crm_rule_power_group")->where($data)->find();
            if($has){
                \exception("小组名已存在");
            }else{
                $data["group_id"]=db("crm_rule_power_group")->insertGetId($data);

            }
            $this->successTerminate($data);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        } 
    }
    public function getgroup(Request $request){
        $StaffModel = new \app\crm\model\Staff();
        $data=db("crm_rule_power_group")->select();
        return $data;
    }
    public function saveuserrole(Request $request){
        try{
            $StaffModel = new \app\crm\model\Staff();
            $params = delToken($request->get());
            $staff_id=trim($params["staff_id"]);
            $arr=db("crm_rule_power_user")->alias("pu")->join("sh_crm_staff u","pu.staff_id=u.staff_id")->where("pu.staff_id='{$staff_id}'")->field("pu.power_user_id,u.staff_id,u.staff_name")->find();
            $power=db("crm_rule_power")->where("type=1 and obj_id={$arr["power_user_id"]}")->find();
            $data=$params;unset($data["staff_id"]);
            if($power){
                db("crm_rule_power")->where("type=1 and obj_id={$arr["power_user_id"]}")->update($data);
            }else{
                $data["type"]=1;
                $data["obj_id"]=$arr["power_user_id"];
                db("crm_rule_power")->insert($data);
            }
            $this->successTerminate($data);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function getuserrole(Request $request){
        $model=new CusareaModel();
        $params = delToken($request->get());
        $staff_id=trim($params["staff_id"]);
        $arr=db("crm_rule_power_user")->alias("pu")->join("sh_crm_staff u","pu.staff_id=u.staff_id")->where("pu.staff_id='{$staff_id}'")->field("pu.power_user_id,u.staff_id,u.staff_name")->find();
        $power=db("crm_rule_power")->where("type=1 and obj_id={$arr["power_user_id"]}")->find();
        if(!$power){
            $power=["check_p"=>0,"add_p"=>0,"update_p"=>0,"delete_p"=>0,"down_p"=>0,"he_p"=>0,"re_p"=>0,"yaoqin_p"=>0];
        }
        $data["user"]=$arr;
        $data["power"]=$power;
        return $data;
    }
    public function getgrouprole(Request $request){
         $model=new CusareaModel();
        $params = delToken($request->get());
        $group_id=trim($params["group_id"]);
        $arr=db("crm_rule_power_group")->alias("pu")->where("pu.group_id='{$group_id}'")->find();
        $power=db("crm_rule_power")->where("type=2 and obj_id={$arr["group_id"]}")->find();
        if(!$power){
            $power=["check_p"=>0,"add_p"=>0,"update_p"=>0,"delete_p"=>0,"down_p"=>0,"he_p"=>0,"re_p"=>0,"yaoqin_p"=>0];
        }
        $data["group"]=$arr;
        $data["power"]=$power;
        $user=db("crm_rule_power_user")->alias("u")->join("crm_staff s","u.staff_id=s.staff_id")->where(["u.group_id"=>$group_id])
        ->field("u.staff_id,s.staff_name")->select();
        $data["user"]=$user;
        return $data;
    }
    public function savegrouprole(Request $request){
        try{
            $StaffModel = new \app\crm\model\Staff();
            $params = delToken($request->get());
            $group_id=trim($params["group_id"]);
            $ustr=trim($params["ustr"]);
            $arr=db("crm_rule_power_group")->alias("pu")->where("pu.group_id='{$group_id}'")->find();
            $power=db("crm_rule_power")->where("type=2 and obj_id={$arr["group_id"]}")->find();
            $data=$params;unset($data["group_id"]);unset($data["ustr"]);
            if($power){
                db("crm_rule_power")->where("type=2 and obj_id={$arr["group_id"]}")->update($data);
            }else{
                $data["type"]=2;
                $data["obj_id"]=$arr["group_id"];
                db("crm_rule_power")->insert($data);
            }
            db("crm_rule_power_user")->where(["group_id"=>$group_id])->update(["group_id"=>0]);
            if($ustr)
                db("crm_rule_power_user")->where("staff_id in ($ustr)")->update(["group_id"=>$group_id]);
            $this->gogroupnum();
            $this->successTerminate($data);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function gogroupnum(){
        $StaffModel = new \app\crm\model\Staff();
        $arr=db("crm_rule_power_group")->select();
        foreach ($arr as $k => $v) {
            # code...
            $num=db("crm_rule_power_user")->where(["group_id"=>$v["group_id"]])->count();
            if(!$num){
                $num=0;
            }
            db("crm_rule_power_group")->where(["group_id"=>$v["group_id"]])->update(["num"=>$num]);
        }
    }
     /**
     * 员工简单列表接口
     */
    public function easy(Request $request){
        $StaffModel = new \app\crm\model\Staff();

        try {
            $params = delToken($request->get());
            $ids=db("crm_rule_staff")->column("staff_id");
            foreach ($ids as $k => $v) {
                # code...
                $ids[$k]="'{$ids[$k]}'";
            }
            $ids=implode(',',$ids);
            $data = $StaffModel->easySearch3($params,$ids);

            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
      /**
     * 员工简单列表接口
     */
    public function easy2(Request $request){
        $StaffModel = new \app\crm\model\Staff();

        try {
            $params = delToken($request->get());
            $ids=db("crm_rule_power_user")->column("staff_id");
            foreach ($ids as $k => $v) {
                # code...
                $ids[$k]="'{$ids[$k]}'";
            }
            $ids=implode(',',$ids);
            $data = $StaffModel->easySearch3($params,$ids);

            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    
    public function changearea(Request $request){
        try {
            $model=new CusareaModel();
            $params = delToken($request->get());
            $staff_id=trim($params["staff_id"]);
            $area_list=trim($params["area_list"]);
            db("crm_rule_area")->where(["staff_id"=>$staff_id])->update(["area_list"=>$area_list]);
          $this->successTerminate($params);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function delpoweruser(Request $request){
        try{
            $model=new CusareaModel();
            $params = delToken($request->get());
            $staff_id=trim($params["staff_id"]);
           
                db("crm_rule_power_user")->where(["staff_id"=>$staff_id])->delete();
            $this->gogroupnum();
            $this->successTerminate($params);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function changegroup(Request $request){
        try{
            $model=new CusareaModel();
            $params = delToken($request->get());
            $staff_id=trim($params["staff_id"]);
            $group_id=trim($params["group_id"]);
                db("crm_rule_power_user")->where(["staff_id"=>$staff_id])->update(["group_id"=>$group_id]);
            $this->gogroupnum();
            $this->successTerminate($params);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function addpoweruser(Request $request){
        //crm_rule_power_user
        try{
            $model=new CusareaModel();
            $params = delToken($request->get());
            $staff_id=trim($params["staff_id"]);
            $has=db("crm_rule_power_user")->where(["staff_id"=>$staff_id])->find();
            if(!$has)
                db("crm_rule_power_user")->insert(["staff_id"=>$staff_id]);
            $params["group_id"]=0;
            $this->successTerminate($params);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function addareauser(Request $request){
        try{
            $model=new CusareaModel();
            $params = delToken($request->get());
            $staff_id=trim($params["staff_id"]);
            $has=db("crm_rule_area")->where(["staff_id"=>$staff_id])->find();
            if(!$has)
                db("crm_rule_area")->insert(["staff_id"=>$staff_id]);
            $this->successTerminate($params);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    public function poweruser(Request $request){
        $model=new CusareaModel();
        $params = delToken($request->get());
        $query=trim($params["query"]);
        $where="1=1 ";
        if($query){
            $where="b.staff_name like '%{$query}%' ";
        }
        $options=trim($params["options"]);
        
        if($options=="全部"){
            $where.=" and 1=1";
            
        }else if($options=="独立授权"){
            $where.="and a.group_id=0";
        }else{
            $group_id=db("crm_rule_power_group")->where(["group_name"=>$options])->value("group_id");
             $where.="and a.group_id={$group_id}";
        }
        $arr=db("crm_rule_power_user")->alias("a")->join("sh_crm_staff b","a.staff_id=b.staff_id")->where($where)->field("a.staff_id,b.staff_name,a.group_id")->select();
        $data=[];
        foreach ($arr as $k => $v) {
            # code...
            $tmp["staff_id"]=$v["staff_id"];
            $tmp["staff_name"]=$v["staff_name"];
            $tmp["empower_way"]="独立授权";
            $tmp["group_id"]=$v["group_id"];
            if($v["group_id"]){
                //$tmp["area"]=db("client_region")->where("region_id in ({$v["area_list"]})")->field("region_id,region_name")->select();
                $tmp["empower_way"]=db("crm_rule_power_group")->where("group_id={$v["group_id"]}")->value("group_name");
            }
            $data[]=$tmp;
        }
        return $data;
    }
     public function areauser(Request $request){
        $model=new CusareaModel();
        $params = delToken($request->get());
        $query=trim($params["query"]);
        $where="1=1";
        if($query){
            $where="b.staff_name like '%{$query}%'";
        }
        $arr=db("crm_rule_area")->alias("a")->join("sh_crm_staff b","a.staff_id=b.staff_id")->where($where)->field("a.staff_id,b.staff_name,a.area_list")->select();
        $data=[];
        foreach ($arr as $k => $v) {
            # code...
            $tmp["staff_id"]=$v["staff_id"];
            $tmp["staff_name"]=$v["staff_name"];
            $tmp["area"]=[];
            if($v["area_list"]){
                $tmp["area"]=db("client_region")->where("region_id in ({$v["area_list"]})")->field("region_id,region_name")->select();
            }
            $data[]=$tmp;
        }
        return $data;
    }
    public function tomanager(Request $request){
        try{
            $model=new CusareaModel();
            $params = delToken($request->get());
            $staff_id=$params["staff_id"];
            $has=db("crm_rule_staff")->where(["staff_id"=>$staff_id])->find();
              $c=$this->getnum();
            if($has){
                db("crm_rule_staff")->where(["staff_id"=>$staff_id])->update(["is_manager"=>1]);
            }else{
              
                if($c>=10){
                    \exception("可使用当前应用的人数上限为10");
                }else{
                    db("crm_rule_staff")->insert(["staff_id"=>$staff_id,"is_manager"=>1]);
                    $c++;
                }
            }
            $this->successTerminate($c);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
        
    }
    public function remanager(Request $request){
        try{
            $model=new CusareaModel();
            $params = delToken($request->get());
            $staff_id=$params["staff_id"];
            $c=db("crm_rule_staff")->where(["staff_id"=>$staff_id])->update(["is_manager"=>0]);
            $c=$this->getnum();
            $this->successTerminate($c);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function touser(Request $request){
        try{
            $model=new CusareaModel();
            $params = delToken($request->get());
            $staff_id=$params["staff_id"];
            $has=db("crm_rule_staff")->where(["staff_id"=>$staff_id])->find();
            $c=$this->getnum();
            if(!$has){
                if($c>=10){
                    \exception("可使用当前应用的人数上限为10");
                }else{
                    db("crm_rule_staff")->insert(["staff_id"=>$staff_id,"is_manager"=>0]);
                    $c++;
                }
            }
            $this->successTerminate($c);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function reuser(Request $request){
        try{
            $model=new CusareaModel();
            $params = delToken($request->get());
            $staff_id=$params["staff_id"];
            $has=db("crm_rule_staff")->where(["staff_id"=>$staff_id])->find();
            $c=$this->getnum();
            if($has){
                db("crm_rule_staff")->where(["staff_id"=>$staff_id])->delete();
                $c--;
            }
            $this->successTerminate($c);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
     /**
     * 部门列表接口
     */
    public function all(Request $request){
        $model=new CusareaModel();
        $params = delToken($request->get());
        $query=trim($params["query"]);
                if(!$query){
                   $dep=db("crm_department")->field('department_id, department_name as title, parent_id')
                        ->where('is_delete', 0)->select();
                     $where="is_downstream=1";
                }else{
                    $dep=[];
                     $where="staff_name like '%{$query}%' or phone like '%{$query}%' and is_downstream=1 ";
                }
     
       
        $sta=db("crm_staff")->field("staff_id,staff_name as title,department_id as parent_id")->where($where)->select();
        $manager=db("crm_rule_staff")->where("is_manager=1")->column("staff_id");
        $user=db("crm_rule_staff")->column("staff_id");
        $all=[];
        foreach ($dep as $k => $v) {
            $dep[$k]["is_dep"]=1;
            $dep[$k]["is_disable"]=true;
            $dep[$k]["is_disable1"]=true;
            $dep[$k]["is_checked"]=false;
            $dep[$k]["is_checked1"]=false;
            $all[]=$dep[$k];
        }
        foreach ($sta as $k => $v) {
            # code...
            $sta[$k]["is_dep"]=0;
            $sta[$k]["department_id"]=-999;
            $sta[$k]["is_disable"]=false;
            $sta[$k]["is_disable1"]=false;
           
            if(in_array($v["staff_id"],$manager)){
                $sta[$k]["is_checked"]=true;
                $sta[$k]["is_checked1"]=true;
            }else if(in_array($v["staff_id"],$user)){
                $sta[$k]["is_checked"]=true;
                $sta[$k]["is_checked1"]=false;
            }else{
                 $sta[$k]["is_checked"]=false;
                $sta[$k]["is_checked1"]=false;
            }
            if($query){
                $sta[$k]["children"]=[];
            }
            $all[]=$sta[$k];
        }
        if(!$query){
            $all= $this->tree($all, 0);
        }
        return $all;
    }
     /**
     * 允许限制级数
     * @param $categories
     * @param int $pid
     * @param int $levelLimit
     * @param int $level
     * @return array
     */
    private function tree($categories, $pid = 0, $levelLimit = 0, $level = 1)
    {
        $children = [];
        foreach ($categories as $category) {
            if ($category['parent_id'] === $pid) {

                if ($levelLimit === 0 || $level < $levelLimit) {
                    $category['is_show'] = false;
                    $category['children'] = $this->tree($categories, $category['department_id'], $levelLimit, $level + 1);
                }

                $children[] = $category;
            }
        }
        return $children;
    }
    //工作汇报权限
    public function workreportrole(Request $request){
        try{
            $model=new CusareaModel();
            $params = delToken($request->param());
            $staff_id=$params["staff_id"];
            $has=db("crm_report_staff")->where(["staff_id"=>$staff_id,"is_manager"=>1])->find();
            $c=[];
            if($has){
                $c["is_manager"]=1;
                $c["staff_list"]=[];
                $c["department_list"]=[];
            }else{
                $c["is_manager"]=0;
                $list=db("crm_report_check_role")->where(["staff_id"=>$staff_id])->find();
                if($list){
                    if($list["staff_list"])
                        $c["staff_list"]=explode(',',$list["staff_list"]);
                    else
                        $c["staff_list"]=[];
                    if($list["depart_list"])
                        $c["department_list"]=explode(',',$list["depart_list"]);
                    else
                        $c["department_list"]=[];
                }else{
                    $c["staff_list"]=[];
                    $c["department_list"]=[];
                }
            }

            $this->successTerminate($c);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
     //crm设置权限
    public function crmrole(Request $request){
        try{
            $model=new CusareaModel();
            $params = delToken($request->param());
            $staff_id=$params["staff_id"];
            $has=db("crm_rule_staff")->where(["staff_id"=>$staff_id])->find();
            $c=[];
            if($has){
                $c["hasrole"]=1;
                if($has["is_manager"]==1){
                    $c["is_manager"]=1;
                    $c["area_list"]=[];
                    $c["power"]=[];
                }else{
                    $c["is_manager"]=0;
                    $area_list=db("crm_rule_area")->where(["staff_id"=>$staff_id])->value("area_list");
                    if($area_list){
                        $c["area_list"]=explode(',',$area_list);
                    }else{
                        $c["area_list"]=[];
                    }
                    $poweruser=db("crm_rule_power_user")->where(["staff_id"=>$staff_id])->find();
                    if($poweruser){
                        if($poweruser["group_id"]){
                            $power=db("crm_rule_power")->where(["obj_id"=>$poweruser["group_id"],"type"=>2])->field("check_p,add_p,update_p,delete_p,down_p,he_p,re_p,yaoqin_p")->find();
                        }else{
                            $power=db("crm_rule_power")->where(["obj_id"=>$poweruser["staff_id"],"type"=>1])->field("check_p,add_p,update_p,delete_p,down_p,he_p,re_p,yaoqin_p")->find();
                        }
                        if(!$power){
                            $power=["check_p"=>0,"add_p"=>0,"update_p"=>0,"delete_p"=>0,"down_p"=>0,"he_p"=>0,"re_p"=>0,"yaoqin_p"=>0];
                        }
                    }else{
                        $power=["check_p"=>0,"add_p"=>0,"update_p"=>0,"delete_p"=>0,"down_p"=>0,"he_p"=>0,"re_p"=>0,"yaoqin_p"=>0];
                    }
                    $c["power"]=$power;
                }
            }else{
                $c["hasrole"]=0;
            }
            $this->successTerminate($c);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    //可查看客户分类
    public function couldcustype(Request $request){
        try{
            $model=new CusareaModel();
            $params = delToken($request->param());
            $staff_id=$params["staff_id"];
            $dep_id=db("crm_staff")->where(["staff_id"=>$staff_id])->value("department_id");
            $cust=db("client_category")->select();
            $cus=[];
            foreach ($cust as $k => $v) {
                # code...
                if($v["seetype"]==0){
                    $cus[]=$v;
                }else{
                    if($v["staff_list"]){
                        $st=explode(',',$v["staff_list"]);
                        if(in_array($staff_id,$st)){
                            $cus[]=$v;
                        }
                    }else{
                        if($v["department_list"]){
                            $dl=explode(',',$v["department_list"]);
                            if(in_array($dep_id,$dl)){
                                $cus[]=$v;
                            }
                        }
                    }
                }
            }
            $this->successTerminate($cus);
        }catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
}
